package com.finger.forest;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.esri.arcgisruntime.geometry.GeodeticCurveType;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.LinearUnit;
import com.esri.arcgisruntime.geometry.LinearUnitId;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.Patrol;
import com.finger.forest.model.PatrolTrailModel;
import com.finger.forest.model.SignModel;
import com.finger.forest.model.WorkLogModel;
import com.finger.forest.service.GpsService;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import org.w3c.dom.Text;

import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 考勤打卡
 */
public class SignActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "SignActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 经度
     */
    @BindView(R.id.tv_sign_longtitude)
    TextView signLongtitudeTv;

    /**
     * 纬度
     */
    @BindView(R.id.tv_sign_latitude)
    TextView signLatitudeTv;

    /**
     * 日期
     */
    @BindView(R.id.tv_date)
    TextView dateTv;

    /**
     * 月份
     */
    @BindView(R.id.tv_month)
    TextView monthTv;

    /**
     * 日历布局
     */
    @BindView(R.id.layout_calendar)
    LinearLayout calendarLayout;

    /**
     * 打卡
     */
    @BindView(R.id.layout_sign)
    LinearLayout signLayout;

    /**
     * 打卡记录
     */
    @BindView(R.id.layout_sign_record)
    LinearLayout signRecordLayout;

    /**
     * 上班打卡或下班打卡
     */
    @BindView(R.id.tv_sign)
    TextView signTv;

    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;

    /**
     * 时间
     */
    @BindView(R.id.tv_time)
    TextView timeTv;

    /**
     * 责任区
     */
    @BindView(R.id.tv_area)
    TextView areaTv;

    /**
     * 上班打卡时间
     */
    private String startSignTime;

    /**
     * 下班打卡时间
     */
    private String endSignTime;

    private final LinearUnit mUnitOfMeasurement = new LinearUnit(LinearUnitId.KILOMETERS);

    public static final int MSG_ONE = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //通过消息的内容msg.what  分别更新ui
            switch (msg.what) {
                case MSG_ONE:
                    //获取网络时间
                    //请求网络资源是耗时操作。放到子线程中进行
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getNetTime();
                        }
                    }).start();
                    break;
                default:
                    break;
            }
        }
    };

    //开一个线程继承Thread
    public class TimeThread extends Thread {
        //重写run方法
        @Override
        public void run() {
            super.run();
            do {
                try {
                    //每隔一秒 发送一次消息
                    Thread.sleep(1000);
                    Message msg = new Message();
                    //消息内容 为MSG_ONE
                    msg.what = MSG_ONE;
                    //发送
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private void getNetTime() {
        URL url = null;//取得资源对象
        try {
            url = new URL("http://www.baidu.com");
            //url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
            URLConnection uc = url.openConnection();//生成连接对象
            uc.connect(); //发出连接
            long ld = uc.getDate(); //取得网站日期时间
            DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(ld);
            final String format = formatter.format(calendar.getTime());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (timeTv != null){
                        timeTv.setText(format);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Handler handlerPost = new Handler();

    @Override
    protected int setView() {
        return R.layout.activity_sign;
    }

    @Override
    protected void receiveData() {
        //判断是上班打卡或下班打卡
        querySignByDate();
    }

    @Override
    protected void initializeView() {


        //获取经纬度、责任区名称
        String locationLongitude = PrefsUtil.getString(SignActivity.this, CommonKey.LOCATION_LONGITUDE);
        String locationLatitude = PrefsUtil.getString(SignActivity.this, CommonKey.LOCATION_LATITUDE);
        String areaName = PrefsUtil.getString(SignActivity.this, CommonKey.AREA_NAME);
        signLongtitudeTv.setText(locationLongitude);
        signLatitudeTv.setText(locationLatitude);
        areaTv.setText(areaName);

        //初始化日期
        dateTv.setText(DateUtil.dateToStr(DateUtil.DATE_FORMAT));

        //初始化月份
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        monthTv.setText(month + "月");

        //初始化日历
        List<Map<String,String>> calList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        while (cal.get(Calendar.MONTH) == (month-1)){
            Map<String,String> mapT = new HashMap<>();
            mapT.put("week", DateUtil.getDayName(cal.get(Calendar.DAY_OF_WEEK)));
            mapT.put("day", cal.get(Calendar.DAY_OF_MONTH)+"");
            calList.add(mapT);
            cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+1);
        }
        for (int i=0;i<calList.size();i++){
            Map<String,String> mapT = calList.get(i);
            LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_calendar,null);
            TextView weekTv = ll.findViewById(R.id.tv_week);
            weekTv.setText(mapT.get("week").toString());
            TextView dayTv = ll.findViewById(R.id.tv_day);
            dayTv.setText(mapT.get("day").toString());
            if (day == Integer.parseInt(mapT.get("day").toString())){
                weekTv.setTextColor(getResources().getColor(R.color.colorBlue));
                dayTv.setTextColor(getResources().getColor(R.color.colorBlue));
            }
            calendarLayout.addView(ll);
        }

        handlerPost.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (scrollView != null){
                    //在该run方法中执行滚动操作
                    scrollView.scrollTo((day-1) * 80, 0);
                }
            }
        }, 2000); // 延迟2秒，再运行splashhandler的run()

        new TimeThread().start();
    }

    private void querySignByDate(){
        String userId = PrefsUtil.getString(this, CommonKey.USER_ID);
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId",userId);
        maps.put("gocreateTime",DateUtil.dateToStr(DateUtil.DATE_FORMAT));
        presenter.querySignByDate(maps);
    }

    @Override
    protected void loadDataFromServer() {

    }

    @OnClick({R.id.btn_back, R.id.layout_sign })
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //打卡
                case R.id.layout_sign:
                    String userId = PrefsUtil.getString(this, CommonKey.USER_ID);
                    String longitude = signLongtitudeTv.getText().toString();
                    String latitude = signLatitudeTv.getText().toString();
                    Log.i(TAG, "打卡经度："+ longitude +"，纬度："+ latitude);
                    Map<String, Object> maps = new HashMap<>();
                    if (signTv.getText().equals("上班打卡")){ //上班打卡
                        maps.put("userid",userId);
                        maps.put("longitude",longitude);
                        maps.put("latitude",latitude);
                        presenter.submitOnSign(maps);

                    } else{ //下班打卡
                        maps.put("checkworkId",signTv.getTag());
                        maps.put("offlongitude",longitude);
                        maps.put("offlatitude",latitude);
                        presenter.submitOffSign(maps);

                        //下班打卡成功后停止Gps服务，停止上传位置坐标
                        Intent mIntent=new Intent(SignActivity.this, GpsService.class) ;
                        stopService(mIntent);//停止服务
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {

            //上班打卡
            case ResponseTag.SUBMIT_ON_SIGN:
                querySignByDate(); //刷新数据
                ToastUtils.show(msg);
                //上班打卡成功后，新增一条巡护记录
                String userId = PrefsUtil.getString(this, CommonKey.USER_ID);
                Map<String, Object> maps = new HashMap<>();
                maps.put("gridUserId",userId);
                maps.put("areaId",PrefsUtil.getString(SignActivity.this, CommonKey.AREA_ID));
                presenter.addPatrolRecord(maps);
                //上班打卡成功后启动Gps服务，上传位置坐标
                Intent mIntent=new Intent(SignActivity.this, GpsService.class) ;
                startService(mIntent);//直接启动服务方式启动
                break;

            //下班打卡
            case ResponseTag.SUBMIT_OFF_SIGN:
                querySignByDate(); //刷新数据
                ToastUtils.show(msg);
                break;

            //查询打卡记录
            case ResponseTag.QUERY_SIGN_RECORD:
                SignModel signModel = (SignModel) model;
                if (signModel != null){
                    signRecordLayout.removeAllViews();
                    signTv.setText("下班打卡");
                    signTv.setTag(signModel.getId());

                    //上班打卡记录
                    LinearLayout llayout = (LinearLayout) LayoutInflater.from(SignActivity.this).inflate(R.layout.item_sign,null);
                    TextView signFlagTv = llayout.findViewById(R.id.tv_sign_flag);
                    TextView signStatusTv = llayout.findViewById(R.id.tv_sign_status);
                    TextView signTimeTv = llayout.findViewById(R.id.tv_sign_time);
                    TextView signAddressTv = llayout.findViewById(R.id.tv_sign_address);
                    TextView signExcepTv = llayout.findViewById(R.id.tv_sign_excep);
                    signFlagTv.setText("上班：");
                    signStatusTv.setText("未打卡");
                    if (signModel.getGowork().equals("1")){
                        //记录上班打卡时间，为计算巡护时长
                        startSignTime = signModel.getGocreateTime();
                        signStatusTv.setText("已打卡");
                        signTimeTv.setText(signModel.getGocreateTime());
                        signAddressTv.setText(signModel.getLongitude()+"，"+signModel.getLatitude());
                        if (signModel.getCoworkresults().equals("0")){
                            signExcepTv.setVisibility(View.VISIBLE);
                            signExcepTv.setText("迟到");
                        }
                    }
                    signRecordLayout.addView(llayout);

                    //下班打卡记录
                    LinearLayout llayout1 = (LinearLayout) LayoutInflater.from(SignActivity.this).inflate(R.layout.item_sign,null);
                    TextView signFlagTv1 = llayout1.findViewById(R.id.tv_sign_flag);
                    TextView signStatusTv1 = llayout1.findViewById(R.id.tv_sign_status);
                    TextView signTimeTv1 = llayout1.findViewById(R.id.tv_sign_time);
                    TextView signAddressTv1 = llayout1.findViewById(R.id.tv_sign_address);
                    TextView signExcepTv1 = llayout1.findViewById(R.id.tv_sign_excep);
                    signFlagTv1.setText("下班：");
                    signStatusTv1.setText("未打卡");
                    if (signModel.getOffwork()!=null && signModel.getOffwork().equals("1")){
                        //记录下班打卡时间，为计算巡护时长
                        endSignTime = signModel.getOffcreateTime();
                        signStatusTv1.setText("已打卡");
                        signTimeTv1.setText(signModel.getOffcreateTime());
                        signAddressTv1.setText(signModel.getOfflongitude()+"，"+signModel.getOfflatitude());
                        if (signModel.getCoworkresults().equals("0")){
                            signExcepTv1.setVisibility(View.VISIBLE);
                            signExcepTv1.setText("早退");
                        }

                        Date date = new Date();
                        //查询巡护轨迹
                        queryPatrolTrail(DateUtil.dateToStr(date), DateUtil.dateToStr(date));
                    }
                    signRecordLayout.addView(llayout1);
                }

                break;

            //新增巡护记录成功，保存巡护ID
            case ResponseTag.ADD_PATRAL_RECORD:
                Log.i(TAG, msg);
                Patrol patrol = (Patrol) model;
                String patrolId = String.valueOf(patrol.getId());
                PrefsUtil.setString(SignActivity.this, CommonKey.PATROL_ID, patrolId);
                break;

            //查询巡护轨迹
            case ResponseTag.QUERY_PATRAL_TRAIL:
                List<PatrolTrailModel> patrolTrailModelList = (List<PatrolTrailModel>) model;
                //计算巡护时长、里程
                calPatrolValue(patrolTrailModelList);
                break;

            default:
                break;
        }
    }

    /**
     * 查询巡护轨迹
     */
    private void queryPatrolTrail(String startTime, String endTime) {
        String userId = PrefsUtil.getString(this, CommonKey.USER_ID);
        Map<String, Object> maps = new HashMap<>();
        maps.put("gridUserId", userId);
        maps.put("startTime", startTime);
        maps.put("endTime", endTime);
        //maps.put("endTime", DateUtil.dateToStr(DateUtil.DATE_FORMAT));
        presenter.queryPatrolTrail(maps);
    }

    /**
     * 计算巡护时长和里程
     *
     * @param list
     */
    private void calPatrolValue(List<PatrolTrailModel> list) {
        double distance = 0;
        if (list.size() > 0){
            Polyline polyline = createPolyline(list);
            Geometry pathGeometry = GeometryEngine
                    .densifyGeodetic(polyline, 1, mUnitOfMeasurement, GeodeticCurveType.GEODESIC);
            distance = GeometryEngine.lengthGeodetic(pathGeometry, mUnitOfMeasurement, GeodeticCurveType.GEODESIC);
        }

        //计算巡护时长、巡护里程
        try {
            double duration = DateUtil.differHours(startSignTime, endSignTime);
            Log.i(TAG, "巡护线路："+distance+"；巡护时长："+duration);
            //更新巡护线路时长和里程
            String patrolId = PrefsUtil.getString(this, CommonKey.PATROL_ID);
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", patrolId);
            maps.put("duration", String.valueOf(duration));
            maps.put("mileage", String.valueOf(distance));
            presenter.updatePatrolInfo(maps);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Polyline createPolyline(List<PatrolTrailModel> list) {
        //创建点集合
        PointCollection borderCAtoNV = new PointCollection(SpatialReferences.getWgs84());
        for (PatrolTrailModel patrolTrail : list) {
            double longtitude = patrolTrail.getLongitude().doubleValue();
            double latitude = patrolTrail.getLatitude().doubleValue();
            borderCAtoNV.add(longtitude, latitude);
        }
        //创建线
        Polyline polyline = new Polyline(borderCAtoNV);
        return polyline;
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }
}
